//
//  AppInfoService.m
//  ScholarsBridge
//
//  Created by guggle on 16/12/12.
//  Copyright © 2016年 mingthink. All rights reserved.
//

#import "AppInfoService.h"
#import "SQLManager.h"

@interface AppInfoService(){
    FMDatabaseQueue *_dbQueue;
}

@end

@implementation AppInfoService

#pragma mark 初始化数据库操作，返回数据库操作实例
- (AppInfoService *)init {
    if (self = [super init]) {
        _dbQueue = [[SQLManager sharedInstance] dbQueue];
    }
    return self;
}

#pragma mark 插入新的数据，会替换原来的数据  只能插入String数据
- (void)insert:(AppInfo *)appInfo {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
        [_dbQueue inDatabase:^(FMDatabase *db) {
            [db executeUpdate:@"delete from AppInfo"];
            [db executeUpdate:@"insert into AppInfo (version, isLogined) values (?, ?)",appInfo.version,[NSString stringWithFormat:@"%d",appInfo.isLogined]];
        }];
    });
}

#pragma mark 查询最新插入的Member
- (void)queryLastOneWithCallBack:(void (^)(AppInfo *appInfo))block {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
        __block AppInfo *appInfo = nil;
        [_dbQueue inDatabase:^(FMDatabase *db) {
            FMResultSet *rs = [db executeQuery:@"SELECT * FROM AppInfo order by _id desc limit 1"];
            if ([rs next]) {
                appInfo = [[AppInfo alloc] init];
                appInfo.version = [rs stringForColumn:@"version"];
                appInfo.isLogined = [[rs stringForColumn:@"isLogined"] intValue];
            }
            [rs close];
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
            block(appInfo);
        });
    });

}

@end
